package com.hmall.order.Intercepter;


import com.hmall.order.mapper.UserMapper;
import com.hmall.user.pojo.User;
import com.hmall.user.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Ms SUN
 * @date 2023/5/14
 */
@Slf4j
@Service
public class UserInterceptor implements HandlerInterceptor {
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");
        if (StringUtils.isBlank(authorization)) {
            log.error("用户未登录");
            return false;
        }
        Long userId = Long.valueOf(authorization);
        User user1 = userMapper.selectById(userId);
        if (user1==null){
            log.error("用户不存在");
            return false;
        }
        UserHolder.setUser(userId);
        log.info("登录成功");
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
